package vip.xiaonuo.modular.reactor;

import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import reactor.core.Reactor;
import reactor.event.Event;
import reactor.function.Consumer;
import vip.xiaonuo.facedoor.modular.memberuser.entity.MemberUser;
import vip.xiaonuo.facedoor.modular.topic.EventTopic;
import vip.xiaonuo.modular.remoteapi.stairs.RemoteStairsConstant;
import vip.xiaonuo.modular.sync.DeviceEvent;
import vip.xiaonuo.modular.ybuildingmemberrl.entity.YBuildingMemberRl;
import vip.xiaonuo.modular.ybuildingmemberrl.mapper.YBuildingMemberRlMapper;
import vip.xiaonuo.modular.ybuildingmemberrl.param.YBuildingMemberRlParam;
import vip.xiaonuo.modular.ydeviceevent.entity.YDeviceEvent;
import vip.xiaonuo.modular.ydeviceevent.mapper.YDeviceEventMapper;
import vip.xiaonuo.modular.yelevatordevice.entity.YElevatorDevice;
import vip.xiaonuo.modular.yelevatordevice.service.YElevatorDeviceService;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

import static reactor.event.selector.Selectors.$;

@Service
public class StarisMemberDeleteListener implements Consumer<Event<MemberUser>>, InitializingBean {

    @Resource
    private YBuildingMemberRlMapper buildingMemberRlMapper;

    @Autowired
    private YElevatorDeviceService elevatorDeviceService;

    @Resource
    private YDeviceEventMapper deviceEventEntityMapper;

    @Autowired
    private Reactor reactor;

    @Override
    public void accept(Event<MemberUser> event) {
        List<YBuildingMemberRl> list = buildingMemberRlMapper.findList(new YBuildingMemberRlParam().setMemberId(event.getData().getId()));
        if (CollectionUtils.isNotEmpty(list)) {
            for (YBuildingMemberRl yBuildingMemberRl : list) {
                yBuildingMemberRl.setDeviceSyncStatus(RemoteStairsConstant.DeviceSyncStatus.DELETE);
                buildingMemberRlMapper.updateById(yBuildingMemberRl);

                // 存在任务表
                YElevatorDevice device = elevatorDeviceService.getById(yBuildingMemberRl.getDeviceId());
                YDeviceEvent deviceEvent = new YDeviceEvent();
                deviceEvent.setDeviceNo(device.getDeviceNo());
                deviceEvent.setType(RemoteStairsConstant.RequestCmd.DELETE_PERSON);
                deviceEvent.setCreateDate(new Date());
                deviceEvent.setSysType(1);
                deviceEvent.setBody(yBuildingMemberRl.getMemberId() + ":" + yBuildingMemberRl.getMemberId());
                deviceEvent.setStatus(DeviceEvent.NEW);
                deviceEventEntityMapper.insert(deviceEvent);
            }
        }
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        reactor.on($(EventTopic.MEMBER_DELETE), this);
    }
}
